package com.totoro.controller;

import lombok.SneakyThrows;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author TOTORO
 * @date 2021/7/6 18:29
 * ck编辑器上传文件
 */
@Controller
@RequestMapping("/ckEditor")
public class EditorUploadController {
    private static final String DEFAULT_SUB_FOLDER_FORMAT_AUTO = "yyyyMMddHHmmss";
    /*
     * 上传图片文件夹
     */
    private static final String UPLOAD_PATH = "D:\\file_upload\\image\\";
    /*
     * tomcat配置的文件路径
     *
     */
    public static final String LOCAL_FILE_PATH = "/static_img/";


    /*
     * 上传图片
     */
    @SneakyThrows
    @RequestMapping(value = "/upload")
    public String imageUpload(@RequestParam("upload") MultipartFile file,
                              @RequestParam("CKEditorFuncNum") String CKEditorFuncNum,
                              HttpServletResponse response,
                              HttpServletRequest request){
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        System.out.println("有文件想要上传");
        PrintWriter out = response.getWriter();
        String name = null;
        name = new String(file.getOriginalFilename().getBytes("iso-8859-1"), "UTF-8");
        String uploadContentType = file.getContentType();
        //处理文件后缀
        String expandedName = "";
        if (uploadContentType.equals("image/pjpeg")
                || uploadContentType.equals("image/jpeg")) {
            // IE6上传jpg图片的headimageContentType是image/pjpeg，而IE9以及火狐上传的jpg图片是image/jpeg
            expandedName = ".jpg";
        } else if (uploadContentType.equals("image/png")
                || uploadContentType.equals("image/x-png")) {
            // IE6上传的png图片的headimageContentType是"image/x-png"
            expandedName = ".png";
        } else if (uploadContentType.equals("image/gif")) {
            expandedName = ".gif";
        } else if (uploadContentType.equals("image/bmp")) {
            expandedName = ".bmp";
        } else {
            //文件格式不符合，返回错误信息
            out.println("<script type=\"text/javascript\">");
            out.println("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum
                    + ",''," + "'文件格式不正确（必须为.jpg/.gif/.bmp/.png文件）');");
            out.println("</script>");
            return null;
        }

        //文件命名并保存到服务器
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        name = UUID.randomUUID()+file.getOriginalFilename();
        String DirectoryName =request.getContextPath()+"/static/img/product";
        try {
            File file1 = new File(request.getServletContext().getRealPath("/static/img/product"),name);
            System.out.println(file1.getPath());
            file.transferTo(file1);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String fileURL =request.getContextPath() + "/static/img/product/"+name;

        // 返回"图像"选项卡和图像在服务器的地址并显示图片
        out.println("<script type=\"text/javascript\">");
        out.println("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ",'" +fileURL+"','')");
        out.println("</script>");
        out.close();
        return null;
    }

}
